package com.cn.controller.admin;

import com.cn.entity.Order;
import com.cn.enums.ErrorMsg;
import com.cn.service.OrderService;
import com.cn.vo.PageResult;
import com.cn.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;

/**
 * 管理员订单管理控制器
 * 处理订单列表、删除、查询等功能
 */
@RestController
@RequestMapping("admin/order")
public class AdminOrderController {

    @Autowired
    private OrderService orderService;

    @GetMapping("list")
    public Result orderList(HttpSession session,
                            @RequestParam(value = "page",required = false) Integer page,
                            @RequestParam(value = "nums",required = false) Integer nums){
        if(session.getAttribute("admin")==null){
            return Result.fail(ErrorMsg.COOKIE_ERROR);
        }
        int p=1;
        int n=8;
        if(null!=page){
            p=page>0?page:1;
        }
        if(null!=nums){
            n=nums>0?nums:8;
        }
        PageResult<Order> pageResult = orderService.getAllOrder(p, n);
        return Result.success(pageResult);
    }

    @GetMapping("delete")
    public Result deleteOrder(HttpSession session,
                              @RequestParam("id") Long id){
        // 参数校验
        if (id == null) {
            return Result.fail(ErrorMsg.PARAM_ERROR);
        }
        
        if(session.getAttribute("admin")==null){
            return Result.fail(ErrorMsg.COOKIE_ERROR);
        }
        if(orderService.deleteOrder(id)){
            return Result.success();
        }
        return Result.fail(ErrorMsg.SYSTEM_ERROR);
    }

    // 按订单号查询订单
    @GetMapping("query")
    public Result queryOrder(HttpSession session,
                             @RequestParam(value = "page",required = false) Integer page,
                             @RequestParam(value = "nums",required = false) Integer nums,
                             @RequestParam(value = "searchValue",required = false) String searchValue){

        if(session.getAttribute("admin")==null){
            return Result.fail(ErrorMsg.COOKIE_ERROR);
        }

        int p=1;
        int n=8;
        if(null!=page){
            p=page>0?page:1;
        }
        if(null!=nums){
            n=nums>0?nums:8;
        }

        if(null == searchValue || "".equals(searchValue)) {
            PageResult<Order> pageResult = orderService.getAllOrder(p, n);
            return Result.success(pageResult);
        } else {
            PageResult<Order> pageResult = orderService.findOrderByNumber(searchValue, p, n);
            return Result.success(pageResult);
        }
    }
}